<?php

namespace App\Http\Controllers\Admins\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admins;
use App\Models\OperationalLogs;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;

class AdminApiController extends Controller
{
    /**
     * 管理员登录（员工登录）
     * @return array
     */
    public function login(): array
    {
        #账号都是手机号
        $phone = request('phone',null);
        if(!$phone){
            return retError([
                'msg'=>'手机号不能为空!'
            ]);
        }else{
            $vp = VerifyMobile($phone,true);
            if($vp['code'] == 0){
                return retError([
                    'msg'=>$vp['msg_zh']
                ]);
            }
        }
        $where = [
            'phone'=>$phone
        ];
        $columns = ['id','phone'];
        $data = Admins::query()->where($where)->first($columns);
        if(!$data){
            return retError([
                'msg'=>'该手机号未注册，请联系管理员'
            ]);
        }
        #验证码或密码登录
        $code = \request('code',null);
        if($code){
            #验证登录
            #验证短信验证码是否正确
            $md5 = 'SMS'.$phone.'-smscode';
            $cacheKey = 'getSMSCode'.':' . md5($md5);
            SmsCodeVetify($cacheKey);
            Cache::forget($cacheKey);
            $token = JWTAuth::fromUser($data);
            if (!$token) {
                return retError([
                    'msg'=>'登录错误，请重新登录',
                ],401);
            }
            $admin_id = $data->id;
        }else{
            #密码登录
            $password = request('password');
            if(!$password){
                return retError([
                    'msg'=>'请输入登录密码',
                ],201);
            }
            $credentials = request(['phone', 'password']);
            $token = auth('admins')->attempt($credentials);
            if (!$token) {
                return retError([
                    'msg'=>'密码错误，请重新输入',
                ],401);
            }
            $admin_id = auth('admins')->id();
        }
//        $username = Auth::user();
//        $logs = [
//            'admin_id'=>$admin_id,
//            'operate_menu'=>OperationalLogs::$operateItem['login'],
//            'operate_item'=>$username,
//            'operate_content'=>'登录',
//        ];
        DB::beginTransaction();
        try{
            #更新上一次登录ID和登陆时间
            $ip = GetIPAddress();
            Admins::query()->where('id',$admin_id)->update([
                'last_login_time'=>Carbon::now()->toDateTimeString(),
                'last_login_ip'=>ip2long($ip),
            ]);
            #日志
//            OperationalLogs::AddOperationalLogs($logs);
            DB::commit();
        }Catch(\Exception $exception){
            DB::rollback();
            return retError([
                'msg'=>$exception->getMessage()
            ]);
        }
        $columns = [
            'id','name','username','avatar','phone','current_identity','activation_code','is_activation',
            'expired_at'
        ];
        $users = Admins::query()->find($admin_id,$columns);
        $result = [
            'users'=>$users,
//            'username'=>$username,
            'token'=>RespondWithToken($token),
        ];
        return ret([
            'data'=>$result,
        ]);
    }

    /**
     * 激活账号
     *
     * @return array
     */
    public function activateAccount(): array
    {
        $admin_id = Auth::user()->id;
        $activation_code = request('activation_code');
        if(!$activation_code){
            return retError([
                'msg'=>'请输入激活码！'
            ]);
        }
        $where = [
            'id'=>$admin_id,
        ];
        $admin_code = Admins::query()->where($where)->value('activation_code');
        if($admin_code != $activation_code){
            return retError([
                'msg'=>'无效的激活码！'
            ]);
        }
        $logs = [
            'admin_id'=>$admin_id,
            'operate_menu'=>OperationalLogs::$operateItem['login'],
            'operate_item'=>'激活账号',
            'operate_content'=>'登录-激活账号',
        ];
        DB::beginTransaction();
        try{
            #todo:有效期暂定激活账号日期基础上增加一年
            Admins::query()->where($where)->update([
                'is_activation'=>'1',
                'expired_at'=>  Carbon::now()->addYear()->toDateTimeString()
            ]);
            #日志
            OperationalLogs::AddOperationalLogs($logs);
            DB::commit();
            return ret([
                'data'=>'账号已激活！'
            ]);
        }Catch(\Exception $exception){
            DB::rollback();
            return retError([
                'msg'=>$exception->getMessage()
            ]);
        }
    }

    /**
     * 通过原密码修改密码
     *
     * @return array
     */
    public function changePassword(): array
    {
        $admin_id = Auth::user()->id;
        $where = [
            'id'=>$admin_id,
        ];
        # old passwords
        $password = request('password');
        if($password) {
            $admin_password = Admins::query()->where($where)->value('password');
            if (!password_verify($password, $admin_password)) {
                return retError([
                    'msg' => '旧密码输入不正确！'
                ]);
            }
        }
        # new password
        return $this->newPassword($where);
    }

    /**
     * 通过短信验证码修改密码
     *
     * @return array
     */
    public function changePasswordUseSmsCode(): array
    {
        $phone = request('phone',null);
        if(!$phone){
            return retError([
                'msg'=>'手机号不能为空!'
            ]);
        }else{
            $vp = VerifyMobile($phone,true);
            if($vp['code'] == 0){
                return retError([
                    'msg'=>$vp['msg_zh']
                ]);
            }
        }
        $code = request('code');
        if($code){
            $md5 = 'SMS'.$phone.'-smscodeforchangepassword';
            $cacheKey = 'getSMSCode'.':' . md5($md5);
            SmsCodeVetify($cacheKey);
        }else{
            return retError([
                'msg'=>'验证码不能为空!'
            ]);
        }
        $admin_id = Auth::user()->id;
        $where = [
            'id'=>$admin_id,
        ];
        # new password
        return $this->newPassword($where);
    }

    /**
     * 切换身份--待完善
     *
     * @return array
     */
    public function changeIdentity(): array
    {
//        $admin = Auth::user();
//        if($admin->current_identity == 'super'){
//            return ret([
//                'data'=>'当前身份为超级管理员，无法切换身份',
//            ]);
//        }
        $identity = request('identity');
        #todo:待定
        DB::beginTransaction();
        try {
            #todo：do something
            #todo：日志
            DB::commit();
            return ret([
                'data' => '身份切换成功！'
            ]);
        } catch (\Exception $exception) {
            DB::rollback();
            return retError([
                'msg' => $exception->getMessage()
            ]);
        }
    }

    /**
     * 刷新token
     *
     * @return array
     */
    public function refreshToken(): array
    {
        $new_token = auth('admins')->refresh();
        $token = RespondWithToken($new_token);
        return ret([
            'data' => $token
        ]);
    }

    /**
     * 退出登录
     *
     * @return array
     */
    public function logout(): array
    {
        $admin_id = Auth::user()->id;
        $username = Auth::user()->username;
        auth('admins')->logout();
        #日志
        $logs = [
            'admin_id'=>$admin_id,
            'operate_menu'=>OperationalLogs::$operateItem['logout'],
            'operate_item'=>$username,
            'operate_content'=>'退出登录',
        ];
        DB::beginTransaction();
        try{
            OperationalLogs::AddOperationalLogs($logs);
            DB::commit();
            return ret([
                'data'=>'退出登录成功',
            ]);
        }Catch(\Exception $exception){
            DB::rollback();
            return retError([
                'msg'=>$exception->getMessage(),
            ]);
        }
    }

    /**
     * @return Authenticatable|null
     */
    public function getAdminInfo(): ?Authenticatable
    {
        return Auth::user();
    }

    /**
     * @param array $where
     * @return array
     */
    public function newPassword(array $where): array
    {
        $new_password = request('new_password');
        if (!$new_password) {
            return retError([
                'msg' => '新密码不能为空！'
            ]);
        }
        # confirm password
        $confirm_password = request('confirm_password');
        if ($new_password != $confirm_password) {
            return retError([
                'msg' => '新密码与确认密码不一致！'
            ]);
        }
        $logs = [
            'admin_id'=>Auth::user()->id,
            'operate_menu'=>'-',
            'operate_item'=>Auth::user()->username,
            'operate_content'=>'修改登录密码',
        ];
        DB::beginTransaction();
        try {
            Admins::query()->where($where)->update([
                'password' => bcrypt($new_password),
            ]);
            #日志
            OperationalLogs::AddOperationalLogs($logs);
            DB::commit();
            #todo：密码修改成功，需要重新登录
            auth('admins')->logout();
            return ret([
                'data' => '密码修改成功！'
            ]);
        } catch (\Exception $exception) {
            DB::rollback();
            return retError([
                'msg' => $exception->getMessage()
            ]);
        }
    }
}
